extractLegend <- function(a.gplot) {
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}


## ITANES
require(memisc)
itanes_2013 <- as.data.frame(as.data.set(spss.system.file("ITA2013_(envers2015_01_19).sav"))) # Not provided
itanes_voted_m5s_2013 <- subset(itanes_2013, d89=='M5S - Five Stars Movement (leader: Grillo)')
itanes_voted_other_than_m5s_2013 <- subset(itanes_2013, d89!='M5S - Five Stars Movement (leader: Grillo)')

df <- subset(itanes_voted_m5s_2013, 
             d45 != "Other" &
               d45 != "Don't remember" &
               d45 != "No answer")

# no vote m5s
df1 <- subset(itanes_voted_other_than_m5s_2013, 
             d45 != "Other" &
               d45 != "Don't remember" &
               d45 != "No answer")

df$d45 <- as.factor(as.character(df$d45))
df$d72_5 <- as.factor(as.character(df$d72_5))
df$left_2008 <- grepl('^PD -|^Sinistra|^PS -|^IdV -', df$d45)
df$left_2008[df$d45=="Didn't vote"] <- NA
df$online_part <-  grepl('A few times|Every day|From time to time', df$d72_5)

df$extreme_2008 <- grepl('^LN -|^Sinistra|^IdV -', df$d45)
df$extreme_sx_2008 <- grepl('|^Sinistra|^IdV -', df$d45)
df$extreme_dx_2008 <- grepl('^LN -', df$d45)

df$d21_3 <- factor(df$d21_3, levels=c("No","Yes"))

# no vote m5s
df1$d45 <- as.factor(as.character(df1$d45))
df1$d72_5 <- as.factor(as.character(df1$d72_5))
df1$left_2008 <- grepl('^PD -|^Sinistra|^PS -|^IdV -', df1$d45)
df1$left_2008[df1$d45=="Didn't vote"] <- NA
df1$online_part <-  grepl('A few times|Every day|From time to time', df1$d72_5)

df1$extreme_2008 <- grepl('^LN -|^Sinistra|^IdV -', df1$d45)
df1$extreme_sx_2008 <- grepl('|^Sinistra|^IdV -', df1$d45)
df1$extreme_dx_2008 <- grepl('^LN -', df1$d45)

df1$d21_3 <- factor(df1$d21_3, levels=c("No","Yes"))

# Fiducia

df_fiducia_parl <- subset(df, d15_1 !="Don't know" & d15_1 !="No answer") 
df_fiducia_part <- subset(df, d15_2 !="Don't know" & d15_2 !="No answer") 

df_fiducia_parl$d15_1 <- factor(df_fiducia_parl$d15_1, levels=c("None at all","Not very much",
                                                                "A fair amount","A great deal"))
df_fiducia_part$d15_2 <- factor(df_fiducia_part$d15_2, levels=c("None at all","Not very much",
                                                                "A fair amount","A great deal"))

df_fiducia_parl$d15_1_bin <- revalue(df_fiducia_parl$d15_1, c("None at all"="No",
                                                              "Not very much"="No",
                                                              "A fair amount"="Yes",
                                                              "A great deal"="Yes"))
df_fiducia_part$d15_2_bin <- revalue(df_fiducia_part$d15_2,  c("None at all"="No",
                                                               "Not very much"="No",
                                                               "A fair amount"="Yes",
                                                               "A great deal"="Yes"))

chisq.test(table(df_fiducia_parl$left_2008, df_fiducia_parl$d15_1))
chisq.test(table(df_fiducia_part$left_2008, df_fiducia_part$d15_2))

# Tables 
prop.table(table(df_fiducia_parl$d15_1_bin))
prop.table(table(subset(df_fiducia_parl, left_2008==TRUE)$d15_1_bin)) -
prop.table(table(subset(df_fiducia_parl, left_2008==FALSE)$d15_1_bin))
# No         Yes 
# -0.03603604  0.03603604 
prop.table(table(df_fiducia_part$d15_2_bin))
prop.table(table(subset(df_fiducia_part, left_2008==TRUE)$d15_2_bin)) -
 prop.table(table(subset(df_fiducia_part, left_2008==FALSE)$d15_2_bin))
# No          Yes 
# 0.007484407 -0.007484407 

# No m5s
df1_fiducia_parl <- subset(df1, d15_1 !="Don't know" & d15_1 !="No answer") 
df1_fiducia_part <- subset(df1, d15_2 !="Don't know" & d15_2 !="No answer") 

df1_fiducia_parl$d15_1 <- factor(df1_fiducia_parl$d15_1, levels=c("None at all","Not very much",
                                                                "A fair amount","A great deal"))
df1_fiducia_part$d15_2 <- factor(df1_fiducia_part$d15_2, levels=c("None at all","Not very much",
                                                                "A fair amount","A great deal"))

df1_fiducia_parl$d15_1_bin <- revalue(df1_fiducia_parl$d15_1, c("None at all"="No",
                                                              "Not very much"="No",
                                                              "A fair amount"="Yes",
                                                              "A great deal"="Yes"))
df1_fiducia_part$d15_2_bin <- revalue(df1_fiducia_part$d15_2,  c("None at all"="No",
                                                               "Not very much"="No",
                                                               "A fair amount"="Yes",
                                                               "A great deal"="Yes"))

chisq.test(table(df1_fiducia_parl$left_2008, df1_fiducia_parl$d15_1))
chisq.test(table(df1_fiducia_part$left_2008, df1_fiducia_part$d15_2))

# Tables 
prop.table(table(df1_fiducia_parl$d15_1_bin))
prop.table(table(subset(df1_fiducia_parl, left_2008==TRUE)$d15_1_bin)) -
  prop.table(table(subset(df1_fiducia_parl, left_2008==FALSE)$d15_1_bin))
# No         Yes 
# -0.08603503  0.08603503 
prop.table(table(df1_fiducia_part$d15_2_bin))
prop.table(table(subset(df1_fiducia_part, left_2008==TRUE)$d15_2_bin)) -
  prop.table(table(subset(df1_fiducia_part, left_2008==FALSE)$d15_2_bin))
# No         Yes 
# -0.03719826  0.03719826 


# Comparison m5s voters and other
prop.table(table(df_fiducia_parl$d15_1_bin))
prop.table(table(df1_fiducia_parl$d15_1_bin))

prop.table(table(df_fiducia_part$d15_2_bin))
prop.table(table(df1_fiducia_part$d15_2_bin))

party_levels <- c('Sinistra Arcobaleno - Left Rainbow (leader: Bertinotti)',
                  'IdV - Italy of Values (leader: Di Pietro)',
                  'PD -  Democratic Party (leader: Veltroni)',
                  'PS - Socialist Party (leader: Boselli)',
                  'DC - Union of Christian and Centre Democrats (leader: Casini)',
                  'PDL - The People of Freedom (leader: Berlusconi)',
                  'LN - Northern League (leader: Bossi)',
                  'Didn\'t vote')

fill_colors <- c("None at all" = "#e6550d", "Not very much" = "#fdae6b", 
                 "A fair amount" ="#a1d99b", "A great deal" = "#31a354")

# Parliament
df_perc_parl <- as.data.frame(prop.table(table(df_fiducia_parl$d45, df_fiducia_parl$d15_1),1))
df_perc_parl$Var1 <- factor(df_perc_parl$Var1, levels=party_levels)
p1 <- ggplot(df_perc_parl, aes(x=Var1, y=Freq, fill=Var2)) + geom_bar(stat='identity') +
  scale_x_discrete(labels=c("SA","IdV","PD","PS","DC","PDL","LN", "Didn't\nvote"), drop=FALSE) +
  scale_y_continuous(labels=scales::percent) +
  labs(x="Trust for parliament", y=NULL) + 
  theme(legend.position="bottom",
        legend.title=element_blank()) +
  scale_fill_manual(values=fill_colors)

df_perc_parl_bin <- as.data.frame(prop.table(table(df_fiducia_parl$left_2008, 
                                                   df_fiducia_parl$d15_1_bin),1))
df_perc_parl_bin$Var1 <- factor(df_perc_parl_bin$Var1, levels = c("TRUE","FALSE"))
line_parl <- ggplot(subset(df_perc_parl_bin, Var2=='No'), 
                    aes(y=Freq/sum(Freq), x=Var2, fill=Var1, order=Var1)) + 
  geom_bar(stat='identity') +
  coord_flip() +
  theme(legend.position="none",
        axis.line.y=element_blank(),axis.text.x=element_blank(),
        axis.text.y=element_blank(),axis.ticks.y=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank()) +
  annotate("text", label=paste0("Left (no trust): ", 
                                round(with(df_perc_parl_bin, Freq[Var1=='TRUE' & Var2=='No'])*100, 2),
                                "%"), x=1, y=0.25, size=2) +
  annotate("text", label=paste0("Right (no trust): ", 
                                round(with(df_perc_parl_bin, Freq[Var1=='FALSE' & Var2=='No'])*100, 2),
                                "%"), x=1, y=0.75, size=2) +
  geom_hline(aes(yintercept=0.5))



# Parties
df_perc_part <- as.data.frame(prop.table(table(df_fiducia_part$d45, df_fiducia_part$d15_2),1))
df_perc_part$Var1 <- factor(df_perc_part$Var1, levels=party_levels)
p2 <- ggplot(df_perc_part, aes(x=Var1, y=Freq, fill=Var2)) + geom_bar(stat='identity') +
  scale_x_discrete(labels=c("SA","IdV","PD","PS","DC","PDL","LN", "Didn't\nvote"), drop=FALSE) +
  scale_y_continuous(labels=scales::percent) +
  labs(x="Trust for parties", y=NULL) +
  theme(legend.position="none")  +
  scale_fill_manual(values=fill_colors)

df_perc_part_bin <- as.data.frame(prop.table(table(df_fiducia_part$left_2008, 
                                                   df_fiducia_part$d15_2_bin),1))
df_perc_part_bin$Var1 <- factor(df_perc_part_bin$Var1, levels = c("TRUE","FALSE"))
line_part <- ggplot(subset(df_perc_part_bin, Var2=='No'), 
                    aes(y=Freq/sum(Freq), x=Var2, fill=Var1, order=Var1)) + 
  geom_bar(stat='identity') +
  coord_flip() +
  theme(legend.position="none",
        axis.line.y=element_blank(),axis.text.x=element_blank(),
        axis.text.y=element_blank(),axis.ticks.y=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank()) +
  annotate("text", label=paste0("Left (no trust): ", 
                                round(with(df_perc_part_bin, Freq[Var1=='TRUE' & Var2=='No'])*100, 2),
                                "%"), x=1, y=0.25, size=2) +
  annotate("text", label=paste0("Right (no trust): ", 
                                round(with(df_perc_part_bin, Freq[Var1=='FALSE' & Var2=='No'])*100, 2),
                                "%"), x=1, y=0.75, size=2) +
  geom_hline(aes(yintercept=0.5))

hist1 <- ggplot_gtable(ggplot_build(p1 + theme(legend.position="none")))
hist2 <- ggplot_gtable(ggplot_build(p2))

line1 <- ggplot_gtable(ggplot_build(line_parl))
line2 <- ggplot_gtable(ggplot_build(line_part))

legend <- extractLegend(p1)
grob1 <- arrangeGrob(hist1, hist2, nrow=1)
grob2 <- arrangeGrob(line1, line2, nrow=1)
row1 <- arrangeGrob(grob1, nrow=1)
row2 <- arrangeGrob(grob2, nrow=1)

grid.arrange(row1, legend, row2, nrow=3, heights=c(11, 2, 3))